package cn.zahuo.SJR.jdbc.JDBC_tools;
import java.sql.*;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import	java.util.Properties;
@SuppressWarnings("ALL")
//工具类
public class Jdbc_tools {
    //    私有成员变量
    private static String url;
    private static String user;
    private static String password;
    private static String driver;
    //    静态代码块只会被调用一次，初始的时候
    static {
        try {
            //        创建properties的集合类
            Properties pro = new Properties();
//        将工具类加载入内存，获取配置文件路径，即src下的properties文件
            ClassLoader classloader = Jdbc_tools.class.getClassLoader();
//            返回一个字符串指定路径的URL
            URL res = classloader.getResource("jdbc.properties");
//            返回路径字符串
            String path = res.getPath();
//           2. 加载文件路径,加载dll文件,FIleReader字符流,相当于打开文件读取
            pro.load(new FileReader(path));
//            3.获取数据，赋值
            url = pro.getProperty("url");
            user = pro.getProperty("user");
            password = pro.getProperty("password");
            driver = pro.getProperty("driver");
//            4.注册驱动
            Class.forName(driver);
        } catch (IOException  | ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    //        获取连接
    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(url, user, password);
    }
    //    释放资源
    public static void close(Statement stmt, Connection connection) {
        if (stmt != null & connection != null) {
            try {
                stmt.close();
                connection.close();
            } catch (SQLException throwables) {
//                    处理初始时的null
                throwables.printStackTrace();
            }
        }
    }
//重写释放资源
    public static void close(ResultSet rs,Statement stmt, Connection connection) {
        if (rs != null & stmt != null & connection != null) {
            try {
                rs.close();
                stmt.close();
                connection.close();
            } catch (SQLException throwables) {
//                    处理初始时的null
                throwables.printStackTrace();
            }
        }
    }
}